package cn.wolfcode.luowowo.website.web.intercepter;

import cn.wolfcode.luowowo.cache.service.IRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeysUtil;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.web.annotation.CheckLoginAnnotation;
import cn.wolfcode.luowowo.website.web.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginIntercepter implements HandlerInterceptor {

    @Reference
    private IRedisService redisService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfo userInfo = null;
        //判断是否为controller处理请求

        if(handler instanceof HandlerMethod){
            HandlerMethod method = (HandlerMethod) handler;

            String token = CookieUtil.getToken(request, response);
            userInfo = redisService.getValueByToken(token);

            //判断是否含有登录检查注解
            if(method.hasMethodAnnotation(CheckLoginAnnotation.class)){
                //判断页面传过来的请求中是否含有token的JsessionId,没有则可能是过期了或者是被清除
                if(CookieUtil.getToken(request,response)!=null){
                    //判断redis中是否含有登录信息,没有则可能过期了或者被flushdb清掉了
                    if (userInfo == null){
                        response.sendRedirect("/login.html");
                        return false;
                    }else {
                        //如果已经登录了,则重新设置cookie失效时间
                        Cookie cookie = new Cookie("token",token);
                        cookie.setPath("/");
                        cookie.setMaxAge(RedisKeysUtil.LOGIN_USER.getTime().intValue());
                        response.addCookie(cookie);
                        return true;
                    }
                }
                response.sendRedirect("/login.html");
                return false;
            }
        }
        //session优化,需要登录且登录了话,我们可以在拦截器中设置seesion作用域
        request.getSession().setAttribute("userInfo",userInfo);
        return true;
    }
}
